package com.xintoucloud.pbs.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.xintoucloud.pbs.dao.MessageSendDao;
import com.xintoucloud.pbs.entity.MessageSend;
import com.xintoucloud.pbs.entity.Organization;
import com.xintoucloud.pbs.entity.OrgnizationVo;
import com.xintoucloud.pbs.model.MessageSendVo;

@Repository
//@Transactional
public class MessageSendDaoImpl implements MessageSendDao {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<MessageSendVo> messageSendList() {
		List<MessageSend> mss  = (List<MessageSend>)sessionFactory.getCurrentSession().createQuery("from MessageSend").list();
		//System.out.println("初始数量:"+mss.size());
		List<MessageSendVo> mvos = new ArrayList<>();
		for(MessageSend ms: mss) {
			StringBuffer orgNames = new StringBuffer();
			orgNames.append("");
			MessageSendVo mvo = new MessageSendVo();
			mvo.setMsid(ms.getMsid());
			mvo.setTitle(ms.getTitle());
			mvo.setContext(ms.getContext());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			mvo.setCreatetime(sdf.format(ms.getCreatetime()));
			
			MessageSend ms1 = ms;
			String[] msr = ms1.getOids().split(",");  //将字符串一","分隔开
			for(String m : msr) {  //将支部的名称循环查出并拼接到一起
				int oid = Integer.parseInt(m);
				String orgName = sessionFactory.getCurrentSession().get(Organization.class, oid).getOname();
				orgNames.append(","+orgName);
			}
			String ons = orgNames.subSequence(1, orgNames.length()).toString();
			//System.out.println("拼接的支部名:"+ons);
			mvo.setOrgName(ons);
			mvos.add(mvo);
			System.out.println("时间:"+mvo.getCreatetime());
		}
		//System.out.println("最终数量:"+mvos.size());
		return mvos;
	}


	
	@Override
	public void save(MessageSend ms) {
		// TODO Auto-generated method stub
	}



	@Override
	public List<OrgnizationVo> orgVoList() {
		List<Object[]> os = sessionFactory.getCurrentSession().createQuery("select o.oid,o.oname from Organization o where osgid=4").list();
		List<OrgnizationVo> ovos = new ArrayList<>();
		for(Object[] o :os) {
			OrgnizationVo ovo = new OrgnizationVo();
			ovo.setOid((int)o[0]);
			ovo.setOname((String)o[1]);
			ovos.add(ovo);
		}
		System.out.println("全体党支部的数量"+ovos.size());
		return ovos;
	}



	@Override
	public void add(MessageSend ms) {
		sessionFactory.getCurrentSession().save(ms);
	}

}
